package ac.github.oa.api.compat

import ac.github.oa.OriginAttribute
import ac.github.oa.api.Debug
import ac.github.oa.api.event.entity.EntityLoadEquipmentEvent
import ac.github.oa.internal.core.attribute.equip.AdaptItem
import ac.github.oa.internal.core.attribute.equip.Slot
import ac.github.oa.internal.core.attribute.equip.SlotVariation
import ac.github.oa.util.Strings.hasString
import com.germ.germplugin.api.GermSlotAPI
import org.bukkit.Bukkit
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.info
import taboolib.platform.util.sendLang

object GermPluginHook {

    val isEnable by lazy { Bukkit.getPluginManager().isPluginEnabled("GermPlugin") }

    val slots: List<String>
        get() = OriginAttribute.module.getStringList("germ-plugin.slots")

    @SubscribeEvent
    fun e(e: EntityLoadEquipmentEvent) {
        if (!isEnable) return
        val player = e.livingEntity as? Player ?: return



        e.list += GermSlotAPI.getGermSlotIdentitysAndItemStacks(player, slots).map {
            AdaptItem(GermPluginSlot(it.key, it.value))
        }

        if (Debug.enable) {
            e.list.filter { it.slot is GermPluginSlot }.forEach {
                val slot = it.slot as GermPluginSlot
            }
        }
    }

    class GermPluginSlot(override val id: String, itemStack: ItemStack?) : Slot(itemStack), SlotVariation {

        override fun getItem(entity: LivingEntity): ItemStack {
            return item
        }

        override fun examine(livingEntity: LivingEntity, adaptItem: AdaptItem, patterns: List<String>): Boolean {
            val orNull = patterns.firstOrNull { it.split(" ")[0] == id }
            if (orNull != null) {
                val split = orNull.split(" ")
                val lore = adaptItem.item.itemMeta?.lore ?: arrayListOf()
                return if (!lore.hasString(split[1])) {
                    livingEntity.sendLang("condition-slot-not-enough", item.itemMeta!!.displayName, split[1])
                    false
                } else true
            }
            return false
        }
    }

}
